package com.sysd.exception;

import com.sysd.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 全局异常处理
 * @author: bsh
 * @date: 2025/6/4 10:58
 */
@ControllerAdvice
@Slf4j
public class GlobalException {
    /**
     * 参数解析失败异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) {
        log.error("{}:参数解析失败", request.getRequestURI(), e);
        return Result.error(new ServiceException(HttpStatus.BAD_REQUEST.value(), "参数解析失败"));
    }

    /**
     * 不支持当前请求方法异常处理
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("{}:不支持当前请求方法", request.getRequestURI(), e);
        return Result.error(new ServiceException(HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持当前请求方法"));
    }

    /**
     * 自定义异常处理
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AbstractException.class)
    @ResponseBody
    public Result<String> handleException(AbstractException e, HttpServletRequest request) {
        log.error("{}:自定义内部异常======{}", request.getRequestURI(), e.getMessage());
        return Result.error(e);
    }

    /**
     * 项目运行异常处理
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> handleException(Exception e, HttpServletRequest request) {
        log.error("{}:服务运行异常", request.getRequestURI(), e);
        return Result.error(new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务运行异常"));
    }
}
